<?php

namespace App\Model\Clickhouse;

use ClickHouseDB\Client;

/**
 * clickhouse的基类
 *
 * @author liangl
 * @DateTime 2020-09-04
 */
class BaseModel
{
    /**
     * 类对象
     */
    static private $instance;

    /**
     * clickhouse 实例
     */
    protected $clickhouse;


    /**
     * 初始clickhouse db config
     */
    private function __construct()
    {
        $clickhouseConf = config('database.clickhouse');
        $this->clickhouse = new Client($clickhouseConf);
        $this->clickhouse->database($clickhouseConf['database']);
    }

    /**
     * 对象实例
     */
    public static function getInstance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 新增数据
     *
     * @param string $table
     * @param array $data example:[[25, '我是样例', '2020-09-04']]
     * @param array $fileds example:['event_id', 'name', 'event_date]
     * @return void
     * @author liangl
     * @DateTime 2020-09-04
     */
    public function insert(string $table, array $data, array $fileds)
    {
        return $this->clickhouse->insert($table, $data, $fileds);
    }

    /**
     * 获取数据列表
     *
     * @param string $sql
     * @return array list 列表 total 总数
     * @author liangl
     * @DateTime 2020-09-04
     */
    public function getList(string $sql)
    {
        $statement = $this->clickhouse->select($sql);

        return ['list' => $statement->rows(), 'total' => $statement->countAll()];
    }

    /**
     * 获取单条数据
     *
     * @param string $sql
     * @return array
     * @author liangl
     * @DateTime 2020-09-04
     */
    public function getInfo(string $sql)
    {
        $statement = $this->clickhouse->select($sql);
        return $statement->fetchOne();
    }
}
